import shutil
import sys
import os
sys.path.append(os.getcwd())
from impl.importWallet_linea import WalletUtil
from logic.nft2me_auto import linea_auto_nft2me
import threading
import time


class MainLogic():
    EXTENSION_PATH = os.path.join(os.getcwd(), "lib", "metamask.crx")

    
    EXTENSION_ID = 'nkbihfbeogaeaoehlefnkodbefgpgknn'
    executablePath = os.path.join(os.getcwd(), "lib", "chromedriver.exe")
    password = 'm,./1234'

    def __init__(self, display) -> None:
        self.display = display

    def readWord(self):
        filename = os.getcwd() + "/lib/config.txt"
        word_list = []
        # 逐行读取文件并将助记词存储到数组中
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()  # 去除行首行尾的空白字符
                if line and not line.startswith('#'):
                    word_list.append(line)
        return word_list

    def delete_file(self, word):
        file_path = os.getcwd() + "/cache/" + word
        if os.path.exists(file_path):
            shutil.rmtree(file_path)
            print(f"文件 {file_path} 删除成功")
            # 循环等待文件不存在
            while os.path.exists(file_path):
                time.sleep(0.1)
        else:
            print(f"文件 {file_path} 不存在")

    def WriteUnfinish(self, word):
        filename = os.getcwd() + "/lib/unfinish.txt"

        # 将字符按行分割
        lines = word.split("\n")

        # 过滤掉以"#"开头的行
        filtered_lines = [line for line in lines if not line.startswith("#")]

        # 读取文件内容
        existing_lines = []
        if os.path.exists(filename):
            with open(filename, 'r', encoding='utf-8') as file:
                existing_lines = file.readlines()
        # 比对去除重复的行
        for line in filtered_lines:
            if line.strip() not in existing_lines:
                existing_lines.append(line)

         # 将过滤后的行重新组合成字符串
        output_text = "\n".join(existing_lines)

        with open(filename, 'w', encoding='utf-8') as file:
            file.write(output_text)

    def readUnfinishWord(self):
        filename = os.getcwd() + "/lib/unfinish.txt"
        word_list = []
        # 逐行读取文件并将助记词存储到数组中
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()  # 去除行首行尾的空白字符
                if line and not line.startswith('#'):

                    word_list.append(line)
        return word_list

    def Writefinish(self, word):
        filename = os.getcwd() + "/lib/finish.txt"

        # 将字符按行分割
        lines = word.split("\n")

       # 过滤掉以"#"开头的行
        filtered_lines = [line for line in lines if not line.startswith("#")]

        # 读取文件内容
        existing_lines = []
        if os.path.exists(filename):
            with open(filename, 'r', encoding='utf-8') as file:
                existing_lines = file.readlines()
         # 比对去除重复的行
        for line in filtered_lines:
            if line.strip() not in existing_lines:
                existing_lines.append(line)

         # 将过滤后的行重新组合成字符串
        output_text = "\n".join(existing_lines)

        with open(filename, 'w', encoding='utf-8') as file:
            file.write(output_text)

    def readfinishWord(self):
        filename = os.getcwd() + "/lib/finish.txt"
        word_list = []
        # 逐行读取文件并将助记词存储到数组中
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()  # 去除行首行尾的空白字符
                if not line.startswith('#'):

                    word_list.append(line)
        return word_list

    def delete_lines_with_keyword(self, keyword):
        # 打开原始文件并读取内容
        with open(os.getcwd() + "/lib/unfinish.txt", 'r') as file:
            lines = file.readlines()

        # 找到包含关键字的行的索引
        delete_indices = [i for i, line in enumerate(lines) if keyword in line]

        # 删除找到的行
        for index in sorted(delete_indices, reverse=True):
            del lines[index]

        # 将剩余的行写回原始文件
        with open(os.getcwd() + "/lib/unfinish.txt", 'w') as file:
            file.writelines(lines)

    # 失败临时记录
    count_ = None

    def run(self):
        word_list = self.readWord()
        finish_list = self.readfinishWord()
        # 如果完成列表为空直接执行
        if not finish_list:
            try:
                thread = threading.Thread(
                    target=self.Auto_logic, args=(word_list, None))
                thread.start()

            except Exception as e:
                print(e)
                self.display.displayInfo('钱包' + str(self.count_) + '运行失败')
        else:
            self.display.displayInfo('请执行重新运行')

    def reRun(self):
        word_list = self.readUnfinishWord()
        try:
            thread = threading.Thread(
                target=self.Auto_logic, args=(word_list, 1))
            thread.start()

        except Exception as e:
            print(e)
            self.display.displayInfo('钱包' + str(self.count_) + '重新运行失败')

    def openConfig(self, word):
        def getEnv(word):
            # 输入环境参数得到driver
            wallet = WalletUtil(self.EXTENSION_PATH, word,
                                self.EXTENSION_ID, self.executablePath, self.password)
            driverExt, flag = wallet.importSingleWallet()
            driverExt.get(
                'chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#unlock')
            os.system('pause')
            driverExt.quit()
        try:
            thread = threading.Thread(
                target=getEnv, args=(word,))
            thread.start()
        except Exception as e:
            print(e)
            self.display.displayInfo(word, '配置运行失败')

    # def Auto_logic(self, word_list, flag):
    #     count = 1
    #     for word in word_list:
    #         # 输入环境参数得到driver
    #         driverExt, flag = WalletUtil.importSingleWallet(
    #             WalletUtil, self.EXTENSION_PATH, word, self.EXTENSION_ID, self.executablePath, self.password)

    #         # 运行各类自动逻辑
    #         try:

    #             linea_auto_nft2me.auto_nft2me(
    #                 linea_auto_nft2me, driverExt, flag, self.password, count)
    #             # 成功后记录
    #             self.Writefinish(word)
    #         except Exception as e:
    #             self.count_ = count
    #             self.WriteUnfinish(word)
    #             print(e)
    #             continue
    #         # flag不存在表示不是重新运行
    #     if (flag is not None and self.count_ != count):
    #             self.delete_lines_with_keyword(word)
    #     count += 1

    # 多线程运行

    def Auto_logic(self, word_list, flag):
        count = 0
        lock = threading.Lock()  # 创建一个锁对象

        def process_word(word):
            nonlocal count
            # 输入环境参数得到driver
            wallet = WalletUtil(self.EXTENSION_PATH, word,
                                self.EXTENSION_ID, self.executablePath, self.password)

            driverExt, flag = wallet.importSingleWallet()

            # 创建自动化逻辑对象
            auto_nft2me = linea_auto_nft2me(
                driverExt, flag, self.password, self.display)
            # 运行各类自动逻辑
            try:
                with lock:  # 加锁以确保线程安全
                    auto_nft2me.auto_nft2me()
                    # 成功后记录
                    self.Writefinish(word)
            except Exception as e:
                with lock:  # 加锁以确保线程安全
                    self.count_ = count
                    self.WriteUnfinish(word)
                    print(e)
                    self.display.displayInfo('钱包' + str(count) + '重新运行失败')

        threads = []
        for word in word_list:
            self.display.displayInfo('运行示例' + str(count))
            # 如果为重新运行删除cache文件
            if (flag == 1):
                self.delete_file(word)

            # +++ 修改逻辑如果是重新运行删除cache中的用户配置文件
            thread = threading.Thread(target=process_word, args=(word,))
            threads.append(thread)
            thread.start()
            # flag不存在表示不是重新运行
            if (flag is not None and self.count_ != count):
                with lock:  # 加锁以确保线程安全
                    self.delete_lines_with_keyword(word)
                    self.display.displayInfo('钱包' + str(count) + '重新运行完成')

            with lock:  # 加锁以确保线程安全
                count += 1

        for thread in threads:
            thread.join()  # 等待所有线程执行完成
            self.display.displayInfo('运行完成')


if __name__ == "__main__":
    MainLogic.reRun(MainLogic)
